package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
	"net/http"
	"simulationFulu/controllers"
	"simulationFulu/models"
	"simulationFulu/utils"
	"time"
)

// 初始化
func init() {
	log.SetFormatter(new(utils.Formatter))
	log.SetReportCaller(true)
	log.SetOutput(&lumberjack.Logger{
		Filename:   "./logs/api.log",
		MaxSize:    100, // megabytes
		MaxBackups: 3,
		MaxAge:     28,   // days
		Compress:   true, // disabled by default
	})
	// log.SetOutput(os.Stdout)
	log.SetLevel(log.DebugLevel)
}

func main() {
	log.Info("【simulationFulu】is running!")
	conf := models.GetConfig()
	log.Info("conf:", conf)
	engine := gin.New()

	//日志输出
	// LoggerWithFormatter middleware will write the logs to gin.DefaultWriter
	// By default gin.DefaultWriter = os.Stdout
	engine.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		// your custom format
		logMsg := fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
		log.Info(logMsg) //logrus 记录日志
		return logMsg
	}))

	// 异常捕获
	engine.Use(utils.SetUp())

	// 路由
	engine.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})
	api := engine.Group("api")
	{
		api.POST("/getway", controllers.Input)
	}
	product := engine.Group("product")
	{
		product.POST("/add", controllers.ProductAdd)
		product.POST("/modify", controllers.ProductModify)
		product.GET("/remove", controllers.ProductRemove)
		product.GET("/get", controllers.ProductGet)
		product.GET("/all", controllers.Products)
	}
	callback := engine.Group("callback")
	{
		callback.GET("/authcodeget", controllers.AuthCodeGet)
	}
	// 监听
	engine.Run(":8080")
}

func Test(c *gin.Context) {
	var req models.InputRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, req)
}
